from flask_appbuilder import ModelView
from flask_appbuilder.fieldwidgets import Select2Widget
from flask_appbuilder.models.sqla.interface import SQLAInterface
from app.models import SerialPortCategory, SerialPort, CheckUnit, Profile
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from app import appbuilder, db


def query_serial_for_black():
    cat = db.session.query(SerialPortCategory).filter(SerialPortCategory.name == 'black').first()
    query = db.session.query(SerialPort)
    if cat:
        query = query.filter(SerialPort.category_id == cat.id)
    return query


def query_profile():
    return db.session.query(Profile)


class CheckUnitView(ModelView):
    datamodel = SQLAInterface(CheckUnit)

    list_columns = ['name', 'black.name', 'profile.name', 'temp', 'readme']
    edit_form_extra_fields = {'black': QuerySelectField('Black',
                                                        query_factory=query_serial_for_black,
                                                        widget=Select2Widget()),
                              'profile': QuerySelectField('Profile',
                                                          query_factory=query_profile,
                                                          widget=Select2Widget())
                              }
    add_form_extra_fields = {'black': QuerySelectField('Black',
                                                        query_factory=query_serial_for_black,
                                                        widget=Select2Widget()),
                              'profile': QuerySelectField('Profile',
                                                          query_factory=query_profile,
                                                          widget=Select2Widget())
                              }

    show_template = 'CheckUnit/show_cascade.html'
    add_template = 'CheckUnit/add.html'
    edit_template = 'CheckUnit/edit.html'


# class SerialCategoryView(ModelView):
#     datamodel = SQLAInterface(SerialPortCategory)
#     related_views = [CheckUnitView]


appbuilder.add_view(CheckUnitView, "Check Units", icon="fa-folder-open-o", category="Company")
appbuilder.add_separator("Company")
# appbuilder.add_view(SerialCategoryView, "Departments", icon="fa-folder-open-o", category="Company")
